#导入
import tensorflow as tf 

from tensorflow import keras 

import numpy as np 

#加载数据
imdb = keras.datasets.imdb 

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)

#根据模型和数据进行预处理  
    #对文本进行填充0
x_train = keras.preprocessing.sequence.pad_sequences(
    x_train,
    value=0,
    padding='post',
    maxlen=256         
)
x_test = keras.preprocessing.sequence.pad_sequences(
    x_test,
    value=0,
    padding='post',
    maxlen=256         
)

#构建模型
vocab_size = 10000

model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(1, activation='sigmoid'))

model.summary()


model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])


#模型训练
x_val = x_train[:10000]
partial_x_train = x_train[10000:]

y_val = y_train[:10000]
partial_y_train = y_train[10000:]

model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
#模型测试
results = model.evaluate(test_data,  test_labels, verbose=2)

print(results)


#模型预测

